//
//  AppBridgeTool.swift
//  Runner
//
//  Created by mini2025 on 2025/10/11.
//

import Foundation
import Cocoa
import FlutterMacOS
import UserNotifications

class AppBridgeTool{
    
    public static let shared = AppBridgeTool.init()
    private var channel : FlutterMethodChannel?
    
    
    func createBridget(mainFlutterWindow : NSWindow?){
        if let flutterViewController = mainFlutterWindow?.contentViewController as? FlutterViewController {
            let controller = flutterViewController.engine

            channel = FlutterMethodChannel(name: "btMacos", binaryMessenger: controller.binaryMessenger)
            channel?.setMethodCallHandler { (call, result) in
              if call.method == "TranslateCreateSucNotify" {
                  var key = call.arguments as? String ?? ""
                  self.sendLocalNotification(contentStr: key + "-成功")
                  result(nil)
              }else if call.method == "TranslateCreateReapetNotify" {
                  var key = call.arguments as? String ?? ""
                  self.sendLocalNotification(contentStr: key + "-重复")
                  result(nil)
              } else {
                result(FlutterMethodNotImplemented)
              }
            }
        }
    }
    
    func callFunc(method : String,arguments : Any?,results : FlutterResult?){
        channel?.invokeMethod(method, arguments: arguments, result: results)
    }
    
    
    func sendLocalNotification(contentStr : String) {
        let content = UNMutableNotificationContent()
        content.title = "创建翻译提醒"
//        content.subtitle = "Swift 本地通知"
        content.body = contentStr
        content.sound = .default
        
        // 3 秒后触发
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false)
        let request = UNNotificationRequest(identifier: "macLocalNotice", content: content, trigger: trigger)
        
        UNUserNotificationCenter.current().add(request) { error in
            if let error = error {
                print("通知发送失败: \(error)")
            } else {
                print("通知已发送！")
            }
        }
    }
    
    
}
